<template>
  <div>
    <BasicTable @register="registerTable" class="!p-0 with-more-input">
      <template #form-created>
        <div class="mr-2.5">
          <Button
            v-show="checkboxActive.length > 0"
            @click="showConfirm({ ids: checkboxActive })"
            type="primary"
            danger
            class="mr-2.5"
            >{{ $t('business.batch_delete') }}</Button
          >
          <Button @click="openAddIpModalFun()" type="primary" class="mr-2.5">{{
            $t('business.add_new')
          }}</Button>
          <Button
            @click="openOficialUpdate()"
            type="primary"
            v-if="!areAllFieldsNullOrEmpty(appLink)"
            >{{ $t('business.official_app') }}</Button
          >
          <!-- <Button
            @click="showConfirmApk({})"
            type="primary"
            class="ml-2.5"
            v-if="isHasAuth('70847')"
            >{{ $t('business.add_new_apk') }}</Button
          > -->
        </div>
      </template>
      <template #form-currentType>
        <a-input-group compact style="display: flex; width: 380px" class="t-form-label-com">
          <Select style="width: 50%" v-model:value="currentType" class="br-none">
            <SelectOption :value="1">{{
                $t('table.promotion.promotion_agency_account')
              }}</SelectOption>
            <SelectOption :value="2">{{
                $t('table.promotion.promotion_tunnel_name')
              }}</SelectOption>
            <SelectOption :value="3">{{
                $t('table.promotion.promotion_tunnel_ID')
              }}</SelectOption>
              <SelectOption :value="4">{{ $t('table.risk.report_operate_people') }}</SelectOption>
              <SelectOption :value="6">{{ $t('table.promotion.link_type_1') }}</SelectOption>
            </Select>
            <Input
              style="width: 59%"
              allowClear
              :placeholder="$t('common.inputText')"
              v-model:value="fromSearch"
            />
          </InputGroup>
        </FormItemRest>
      </template>
      <template #form-startDate="{ model, field }">
        <DatePicker
          v-model:value="model[field]"
          :disabledDate="disabledStartDate"
          @change="onStartDateChange"
        />
      </template>
      <template #form-endDate="{ model, field }">
        <DatePicker
          v-model:value="model[field]"
          :disabledDate="disabledEndDate"
          @change="onEndDateChange"
        />
      </template>
      <template #chanelId="{ record }">
        <Button type="link" @click="toChannlStatistics('channel_id', record.id)">{{
          record.id
        }}</Button>
      </template>
      <template #agent="{ record }">
        <Button type="link" @click="toChannlStatistics('username', record.agent_account)">{{
          record.agent_account
        }}</Button>
        <!-- <span class="primary-color cursor ml-1" @click="handleCopyVal(record.agent_account)">{{
          $t('modalForm.finance.common_income.copy')
        }}</span> -->
      </template>
      <template #chanelLink="{ record }">
        <span>{{ getNavLocationLabel(record) }}:</span>
        <span class="ml-1" v-if="record.state == 4"
          >{{ $t('table.promotion.promotion_deleted')
          }}{{ record.link_type == 2 ? `?c=${record.channel_code}` : '' }}</span
        >
        <span class="ml-1" v-else>{{ `https://${record.channel_domain}` }}</span>
        <span class="primary-color cursor ml-1" @click="handleCopy(record)">{{
          $t('modalForm.finance.common_income.copy')
        }}</span>
        <!-- <span class="primary-color cursor ml-1" v-if='record.channel_type==2'>下载</span> -->
      </template>
      <template #chanelapk="{ record }">
        <span class="ml-1" v-if="record.fix == 2 || record.apk == ''"> - </span>

        <span
          class="ml-1 text-green"
          v-if="record.state == 2 || (record.apk == '' && record.fix == 1 && record.app_open != 2)"
        >
          {{ $t('table.promotion.promotion_automatically_packaging') }}
        </span>

        <template
          v-if="
            record.apk == $t('table.promotion.promotion_packaging_failed') &&
            record.state != 2 &&
            record.fix != 2
          "
        >
          <span class="ml-1 text-red">{{ record.apk }}</span>
          <span class="primary-color cursor ml-1" @click="openApk(record, 'update')">
            {{ $t('modalForm.member.member_authorized_update') }}
          </span>
        </template>

        <span class="ml-1" v-if="record.apk == '-' && record.state != 2 && record.fix != 2">
          {{ record.apk }}
        </span>

        <template
          v-if="
            record.apk != $t('table.promotion.promotion_packaging_failed') &&
            record.state != 2 &&
            record.apk != '-' &&
            record.apk != '' &&
            record.fix != 2
          "
        >
          <span class="ml-1">{{ record.apk }}</span>
          <span class="primary-color cursor ml-1" @click="openApk(record)">
            {{ $t('modalForm.member.member_authorized_update') }}
          </span>
          <span class="primary-color cursor ml-1" @click="handleCopyApk(record)">{{
            $t('modalForm.finance.common_income.copy')
          }}</span>
          <span class="primary-color cursor ml-1" @click="downloadApk(record.apk, record.apk_name)">
            {{ $t('component.upload.download') }}
          </span>
        </template>
      </template>
      <!-- <template #chanelapk="{ record }">
        <span class="ml-1" v-if="record.fix == 2 && !isHttpUrl(record.apk)"> - </span>
        <template v-if="record.apk == '打包失败' && record.state != 2 && record.fix != 2">
          <span class="ml-1 text-red">{{ record.apk }}</span>
          <span class="primary-color cursor ml-1" @click="openApk(record, 'update')"> 更新 </span>
        </template>

        <span class="ml-1" v-if="record.apk == '-' && record.state != 2 && record.fix != 2">
          {{ record.apk }}
        </span>

        <template>
          <span
            class="ml-1 text-green"
            v-if="record.state == 2 && record.apk != '-' && record.fix == 1 && record.app_open != 2"
          >
            自动打包中
          </span>

          <template v-else>
            <span class="ml-1">{{ record.apk }}</span>
            <span class="primary-color cursor ml-1" @click="openApk(record)"> 更新 </span>
            <span class="primary-color cursor ml-1" @click="handleCopyApk(record)">{{
              $t('modalForm.finance.common_income.copy')
            }}</span>
            <span
              class="primary-color cursor ml-1"
              @click="downloadApk(record.apk, record.apk_name)"
              >下载</span
            >
          </template>
        </template> -->

      <!-- <template
          v-if="
            record.apk != '打包失败' && record.apk != '-' && record.apk != '' && record.fix != 2
          "
        >
          <span class="ml-1">{{ record.apk }}</span>
          <span class="primary-color cursor ml-1" @click="openApk(record)"> 更新 </span>
          <span class="primary-color cursor ml-1" @click="handleCopyApk(record)">{{
            $t('modalForm.finance.common_income.copy')
          }}</span>
          <span class="primary-color cursor ml-1" @click="downloadApk(record.apk, record.apk_name)"
            >下载</span
          >
        </template> -->
      <!-- </template> -->
      <template #action="{ record }">
        <span
          v-if="isHasAuth('70838')"
          class="px-3 primary-color cursor"
          @click="EditFun(record)"
          >{{ $t('business.common_edit') }}</span
        >
        <span
          v-if="isHasAuth('70840')"
          class="text-red cursor px-3"
          @click="showConfirm({ id: record.id, state: 5 })"
          >{{ $t('common.delText') }}
        </span>
      </template>
    </BasicTable>
    <addChannelLinkModal @register="addIpModal" @success="handleModalSuccess" />
    <updateModal @register="registerUpdateModal" @success="handleModalSuccess" />
    <oficialModal @register="registerOficialModal" :userData="appLink" />
  </div>
</template>

<script lang="ts" setup>
  import { onBeforeMount, onMounted, ref, unref } from 'vue';
  import { BasicTable, useTable } from '@/components/Table';
  import { columns, schemas } from './index.data';
  import { Button } from '@/components/Button';
  import {
    InputGroup,
    Select,
    SelectOption,
    Input,
    DatePicker,
    FormItemRest,
    message,
  } from 'ant-design-vue';
  import {
    deleteChannelLink,
    getBatchUpdateOpen,
    getChannelAppList,
    getChannelList,
  } from '@/api/promotion';
  import addChannelLinkModal from '../../common/components/addChannelLinkModal.vue';
  import { useModal } from '@/components/Modal';
  import dayjs from 'dayjs';
  import { openConfirm } from '@/utils/confirm';
  import { setDateParmas } from '@/utils/dateUtil';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useCopyToClipboard } from '/@/hooks/web/useCopyToClipboard';
  import { useI18n } from '@/hooks/web/useI18n';
  import { isHasAuth } from '/@/utils/authFunction';
  import updateModal from '../../common/components/updateModal.vue';
  import { navLocation } from '../../../common/const';
  import eventBus from '/@/utils/eventBus';
  import { useTreeListStore } from '/@/store/modules/treeList';
  import oficialModal from '../../common/components/oficialModal.vue';

  const emit = defineEmits(['update-event']);

  interface FormModel {
    start_time: Date | null;
    end_time: Date | null;
  }
  const model = ref<FormModel>({
    start_time: null,
    end_time: null,
  });

  const { t } = useI18n();

  const navLocationMap = {
    1: t('table.promotion.promotion_home'),
    2: t('table.promotion.promotion_regis'),
    3: t('table.promotion.promotion_login'),
    4: t('table.promotion.promotion_tiyu'),
    // 2: '娱乐城',
    // 3: '体育',
    // 4: '联盟中心',
  };

  const deviceLocationMap = {
    1: 'Android',
    2: 'IOS',
    3: 'Google Play',
  };

  const { clipboardRef, copiedRef, clearClipboard } = useCopyToClipboard();

  const { createMessage } = useMessage();
  const fromSearch = ref('' as string);
  const checkboxActive = ref([] as any);
  const currentType = ref(1);

  const appLink = ref({});

  const disabledStartDate = (date) => {
    let end_time: any = null;
    if (dayjs(model.value.end_time).valueOf()) {
      end_time = model.value.end_time.valueOf();
    } else {
      end_time = dayjs().endOf('days').valueOf();
    }
    return date.valueOf() > end_time;
  };

  const disabledEndDate = (date) => {
    return (
      date.valueOf() > dayjs().endOf('days').valueOf() ||
      date.valueOf() <= dayjs(model.value.start_time).valueOf()
    );
  };
  const onStartDateChange = (value) => {
    model.value.start_time = value;
  };

  const onEndDateChange = (value) => {
    model.value.end_time = dayjs(value).endOf('days');
  };

  const [addIpModal, { openModal }] = useModal();

  const [registerUpdateModal, { openModal: openModalUpdate }] = useModal();

  const [registerOficialModal, { openModal: openOficialModal }] = useModal();

  const [registerTable, { reload, clearSelectedRowKeys, setPagination }] = useTable({
    api: getChannelList,
    columns: columns,
    bordered: true,
    useSearchForm: true,
    showIndexColumn: false,
    formConfig: {
      schemas,
      showAdvancedButton: false,
      actionColOptions: {
        class: 't-form-col t-form-label-com',
        span: 1,
      },
      showResetButton: false,
    },
    beforeFetch: (params) => {
      setDateParmas(params);
      if (fromSearch.value) {
        params.search_type = currentType.value;
        params.search_value = fromSearch.value;
      }
      return params;
    },
    afterFetch: () => {
      clearSelectedRowKeys();
    },
  });
  function handleCopy(record) {
    clearClipboard();
    if (record.state == 4)
      clipboardRef.value =
        record.link_type == 2
          ? `${t('table.promotion.promotion_deleted')}?c=${record.channel_code}`
          : `${t('table.promotion.promotion_deleted')}`;
    else clipboardRef.value = `https://${record.channel_domain}`;

    if (unref(copiedRef)) {
      createMessage.success(t('business.common_copy_suceess'));
    }
  }

  function downloadApk(url, filename) {
    const link = document.createElement('a');
    link.href = url;
    link.download = filename || 'app.apk'; // 默认文件名为 app.apk
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }

  function handleCopyApk(record) {
    clearClipboard();
    clipboardRef.value = record.apk;

    if (unref(copiedRef)) {
      createMessage.success(t('business.common_copy_suceess'));
    }
  }

  function handleCopyVal(value) {
    if (!value) {
      createMessage.warning(t('table.promotion.promotion_please_copy_content'));
      return;
    }
    clearClipboard();

    clipboardRef.value = value;

    if (unref(copiedRef)) {
      createMessage.success(t('business.common_copy_suceess'));
    }
  }

  function EditFun(record) {
    openModal(true, { category: 1, title: t('table.promotion.promotion_edit_tunnel'), ...record }); //编辑渠道
  }

  function openAddIpModalFun() {
    openModal(true, { category: 2, title: t('table.promotion.promotion_add_tunnel') }); //新增渠道
  }

  function openOficialUpdate() {
    openOficialModal(true, appLink.value); //新增渠道
  }

  async function getOficialLink() {
    const res = await getChannelAppList({});
    appLink.value = JSON.parse(res.data);
    // openOficialModal(true, data); //新增渠道
  }

  function areAllFieldsNullOrEmpty(data) {
    return Object.values(data).every((value) => value === '' || value === null);
  }

  function showConfirm(params) {
    // '操作确认'，'您确定删除该IP地址吗？'
    // '您确定删除该渠道吗？'
    openConfirm(
      t('table.member.member_oprate_tip'),
      t('table.promotion.promotion_remove_tunnel_tip'),
      async () => {
        try {
          const { status, data } = await deleteChannelLink(params);
          if (status) {
            message.success(data);
            setPagination({ current: 1 });
            reload();
          } else message.error(data);
        } catch (e) {
          console.log(e);
        }
      },
    );
  }

  async function showConfirmApk(params) {
    const res = await getChannelList({
      page: 1, //分页页码，数字类型
      page_size: 1000, //分页条数
      search_type: 5,
      search_value: 'apk',
    });
    openConfirm(
      t('table.member.member_oprate_tip'),
      `${t('table.promotion.showConfirmApk_1')}${res.t}${t('table.promotion.showConfirmApk_2')}`,
      async () => {
        try {
          const { status, data } = await getBatchUpdateOpen({
            app_type: 1,
          });
          if (status) {
            message.success(data);
            reload();
          } else message.error(data);
        } catch (e) {
          console.log(e);
        }
      },
    );
  }

  function toChannlStatistics(type, data) {
    switch (type) {
      case 'username':
        emit('update-event', { username: data });
        return;
      case 'channel_id':
        emit('update-event', { channel_id: data });
        return;
    }
  }

  function isHttpUrl(url) {
    const httpRegex = /^https?:\/\//; // 正则表达式，用于匹配以 http:// 或 https:// 开头的 URL
    return httpRegex.test(url);
  }

  function openApk(record: any, type?: any) {
    // if (type) {
    //   record.apk = '';
    //   record.apk_name = '';
    // }
    openModalUpdate(true, record); //新增渠道
  }

  function handleModalSuccess() {
    reload();
  }

  function getNavLocationLabel(record) {
    if (record.nav_location == 5) return t('table.promotion.promotion_imitation_google');
    const matchedLocation = navLocation.find((el) => el.value === record.nav_location);
    return matchedLocation?.label ?? '-';
  }
  onMounted(() => {
    const treeListStore = useTreeListStore();
    treeListStore.initPostChannelTemplateList();
    getOficialLink();
    eventBus.on('Refreshfix', (res: any) => {
      reload();
    });
  });

  onBeforeMount(() => {
    eventBus.off('Refreshfix');
  });
</script>
